package com.westa.smallshop.util;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.westa.smallshop.R;
import com.westa.smallshop.login.LoginActivity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import butterknife.BindString;
import butterknife.BindViews;
import butterknife.ButterKnife;
import io.valuesfeng.picker.PreviewImageActivity;

/**
 * Created by Dune on 16/2/29.
 */
public class Global {


    public final static String CHARACTER_ENCODING = "utf-8";
    public static final String INTEGRAL_SERVER_TAG = "integral";
    public static final String SYSTEM_TAG = "system";
    public static final String TOKEN_TAG = "AUTHORIZATION";
    public static final String TOKEN_NAME_FORMAT_TAG = "TOKEN %s";
    public static final String SYSTEM_NAME = "android";
    public static final String POSITION_TAG = "position_tag";

    public static final String OBJECT_ID_TAG = "object_id";
    public static final String SERVER_ID_TAG = "id";
    public static final String SOURCE_TAG = "source";
    public static final String STATUS_TAG = "status";
    public static final String LOAD_MORE_REQUEST_TAG = "current_time";
    public static final String LOAD_MORE_UPDATE_TIME_REQUEST_TAG = "update_time";
    public static final String ASSETS_URL = "file:///android_asset/%s";
    public static final String DATABASE_NAME = "logistics-db";
    public static final SimpleDateFormat dateMonthFormat = new
            SimpleDateFormat("yyyy年 MM月", Locale.getDefault());
    public static final SimpleDateFormat dateMonthOfDayFormat = new
            SimpleDateFormat("MM月dd日", Locale.getDefault());
    public static final SimpleDateFormat dateMonthLeyFormat = new
            SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    public static final SimpleDateFormat dateTimeFormat = new
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());


    public static void initWebView(WebView webView) {

//        webView.getSettings().setJavaScriptEnabled(true);
        // 防止webview滚动时背景变成黑色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            webView.removeJavascriptInterface("searchBoxJavaBridge_");
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            webView.setBackgroundColor(0x00000000);
        } else {
            webView.setBackgroundColor(Color.argb(1, 0, 0, 0));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.getSettings().setLoadsImagesAutomatically(true);
        } else {
            webView.getSettings().setLoadsImagesAutomatically(false);
        }


        webView.getSettings().setDefaultTextEncodingName("UTF-8");
    }

    public static void initImageView(Fragment fragment, final List<String> images, final TableLayout imageMulti) {
        initImageView(fragment.getActivity(), Glide.with(fragment), images, imageMulti);

    }

    public static void initImageView(Activity activity, final List<String> images, final TableLayout imageMulti) {

        initImageView(activity, Glide.with(activity), images, imageMulti);
    }

    private static void initImageView(final Activity activity, RequestManager requestManager, final List<String> images, final TableLayout imageMulti) {

        imageMulti.setVisibility(images != null && images.size() >= 1 ? View.VISIBLE : View.GONE);
        if (images != null && images.size() >= 1) {

            if (imageMulti.getTag() == null) {
                imageMulti.setTag(new MultiImageViewHolder(imageMulti));
            }
            final MultiImageViewHolder viewHolder = (MultiImageViewHolder) imageMulti.getTag();

            ButterKnife.apply(viewHolder.imageViews, CLEAN);
            ButterKnife.apply(viewHolder.tableRows, GONE);
            for (int i = 0; i < images.size(); i++) {
                viewHolder.getTableRow(i).setVisibility(View.VISIBLE);
                requestManager.load(String.format(viewHolder.thumbnailUrl, images.get(i))).centerCrop()
                        .into(viewHolder.imageViews.get(i));
                viewHolder.imageViews.get(i).setVisibility(View.VISIBLE);
                viewHolder.imageViews.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PreviewImageActivity.startActivity(activity, images, (Integer) v.getTag(R.id.index_tag), true);
                    }
                });
            }
        }
    }

    public static final ButterKnife.Action<View> INDEX = new ButterKnife.Action<View>() {
        @Override
        public void apply(View view, int index) {
            view.setTag(R.id.index_tag, index);
        }
    };

    static final ButterKnife.Action<View> GONE = new ButterKnife.Action<View>() {
        @Override
        public void apply(View view, int index) {
            view.setVisibility(View.GONE);
        }
    };

    static final ButterKnife.Action<ImageView> CLEAN = new ButterKnife.Action<ImageView>() {
        @Override
        public void apply(ImageView view, int index) {
            Glide.clear(view);
            view.setVisibility(View.GONE);
        }
    };

    static class MultiImageViewHolder {

        @BindString(R.string.thumbnail_url)
        String thumbnailUrl;
        @BindViews({R.id.row_1_1, R.id.row_1_2, R.id.row_1_3, R.id.row_2_1, R.id.row_2_2, R.id.row_2_3})
        List<ImageView> imageViews;
        @BindViews({R.id.row_1, R.id.row_2})
        List<TableRow> tableRows;

        public TableRow getTableRow(int position) {

            return tableRows.get(position / 3);
        }

        MultiImageViewHolder(View view) {
            ButterKnife.bind(this, view);
            ButterKnife.apply(imageViews, INDEX);
        }
    }

    public static boolean isUrl(String url) {
        Pattern pattern = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        return pattern.matcher(url).matches();
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static void copyToClipboard(Context context, String s) {

        ((ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE))
                .setPrimaryClip(ClipData.newPlainText(context
                        .getString(R.string.app_name_en), s));
    }
    public static void logout(Context context) {

        UserSPUtils.clear(context);
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }
    @Nullable
    public static String getVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS).versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //版本号
    public static int getVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS).versionCode;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Integer.MAX_VALUE;
    }

//    public static void logout(Context context) {
//
//        UserSPUtils.clear(context);
//        TokenUtil.removeToken(context);
//        Intent intent = new Intent(context, VoiceRegisterActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);
//    }


    public static Calendar timestampTOCalendar(long timestamp) {

        Calendar calendar = Calendar.getInstance();

        Date day = new Date(timestamp * 1000);
        calendar.setTime(day);
        return calendar;
    }

}
